package com.shixun.dds_11.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.shixun.dds_11.context.BaseContext;
import com.shixun.dds_11.dto.GoodsPageDTO;
import com.shixun.dds_11.dto.GoodsPageQueryDTO;
import com.shixun.dds_11.dto.GoodsSelectDTO;
import com.shixun.dds_11.entity.DdsGoods;
import com.shixun.dds_11.entity.DdsNote;
import com.shixun.dds_11.mapper.DdsGoodsMapper;
import com.shixun.dds_11.mapper.DdsNoteMapper;
import com.shixun.dds_11.mapper.UserMapper;
import com.shixun.dds_11.result.PageResult;
import com.shixun.dds_11.service.IDdsGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shixun.dds_11.service.IDdsNoteService;
import com.shixun.dds_11.vo.DdsGoodsSelectVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YSP
 * @since 2024-07-05
 */
@Service
public class DdsGoodsServiceImpl extends ServiceImpl<DdsGoodsMapper, DdsGoods> implements IDdsGoodsService {

    @Autowired
    DdsGoodsMapper ddsGoodsMapper;

    @Autowired
    DdsNoteMapper ddsNoteMapper;

    @Override
    public PageResult pageQuery(GoodsPageDTO goodsPageDTO) {

        QueryWrapper<DdsGoods> queryWrapper=new QueryWrapper<DdsGoods>()
                .eq(!goodsPageDTO.getType().equals("全部"),"type",goodsPageDTO.getType())
                .orderBy(goodsPageDTO.getPrice()>0,true,"price")
                .orderBy(goodsPageDTO.getCount()>0,false,"count")
                .like(goodsPageDTO.getGoods()!=null,"name",goodsPageDTO.getGoods());

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DdsGoods> page=page(new Page<>(goodsPageDTO.getPage(),goodsPageDTO.getPageSize()),queryWrapper);

        return new PageResult(page.getTotal(),page.getRecords());
    }

    @Override
    @Transactional
    public DdsGoods getBygoodsId(Integer id) {
        Integer userId = BaseContext.getCurrentId().intValue();
        DdsNote ddsNote=new DdsNote();
        ddsNote.setGoodsId(id);
        ddsNote.setUserId(userId);
        QueryWrapper<DdsNote>queryWrapper=new QueryWrapper<DdsNote>()
                .eq("goods_id",id);
        ddsNoteMapper.deleteById(id);
        ddsNoteMapper.insert(ddsNote);
        DdsGoods ddsGoods = ddsGoodsMapper.selectById(id);
        ddsGoods.setCount(ddsGoods.getCount()+1);
        ddsGoodsMapper.updateById(ddsGoods);
        return ddsGoods;
    }

    /**
     * 搜素
     * @param goodsSelectDTO
     * @return
     */
    public List<DdsGoodsSelectVO> search(GoodsSelectDTO goodsSelectDTO) {
        List<DdsGoodsSelectVO> list = ddsGoodsMapper.select(goodsSelectDTO);
        return list;
    }
}
